<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\model\Banner;
use think\Db;
use think\Env;
use think\Exception;

class Index extends Api
{
    // 无需登录的接口
    protected $noNeedLogin = '*';
    // 无需鉴权的接口
    protected $noNeedRight = '*';

    /**
     * 获取首页轮播图信息
     * @return \think\response\Json
     */
    public function info()
    {
        try {
            // 从fa_banner表获取轮播图数据
            $query = Db::name('fa_slider')
                ->where('number', 41)
                ->select();
            $result = empty($query)||!empty($query)&&empty($query[0]['image']) ? json_encode([]) : $query[0]['image'];
            $banners = json_decode($result, true);
            if (!is_array($banners)) {
                $banners = [];
            }
            $data = [];
            foreach ($banners as $key=>$banner) {
                if($banners[$key]['status']==0){
                    continue;
                }
                $data[] = [
                    'url' => (isset($banners[$key]['src']) && is_string($banners[$key]['src'])) ? getImg($banners[$key]['src'],750,422) : '',
                    'title' => isset($banners[$key]['title']) ? $banners[$key]['title'] : '',
                    'href' => isset($banners[$key]['href']) ? $banners[$key]['href'] : ''
                ];
            }
            $row = Db::name('fa_course_table_autoplan')
                ->alias('t')
                ->join('eb_apply_form f', 't.apply_form_id = f.id', 'LEFT')
                ->whereRaw("UNIX_TIMESTAMP(CONCAT(t.date, ' ', t.start_time, ':00')) > UNIX_TIMESTAMP(NOW())")
                ->field("MIN(CONCAT(t.date, ' ', t.start_time, ':00')) as min_start_time, t.table_id,f.is_end,f.is_finished,f.is_close")
                ->where('t.status', 1)
                ->where('f.is_end', 0)->where('f.is_finished', 0)->where('f.is_close', 0)
                ->group("t.classes_id")
                ->order("min_start_time asc")
                ->limit(1)
                ->find();
            $table_id = $row ? $row['table_id'] : db::name("fa_course_table")->order("id desc")->value("id");
            if ($table_id) {
                $table = db::name("fa_course_table")->where("id",$table_id)->find();
                if ($table && !empty($table['classes_id'])) {
                    $classesids=explode(",",$table['classes_id']);

                    for($i=0;$i<count($classesids)&&$i<10;$i++){
                        $classes = db::name("eb_classes")->where("id",$classesids[$i])->find();
                        if (!$classes) {
                            continue;
                        }
                        $autoplan = Db::name("fa_course_table_autoplan")
                            ->where("classes_id","=",$classesids[$i])
                            ->whereRaw("UNIX_TIMESTAMP(CONCAT(date, ' ', start_time, ':00')) > UNIX_TIMESTAMP(NOW())")
                            ->order("date asc, start_time asc")
                            ->limit(1)
                            ->find();
                        if (empty($autoplan)) {
                            continue;
                        }
                        $data[] = [
                            'url' => (isset($classes['header_image']) && is_string($classes['header_image'])) ? getImg($classes['header_image'],750,422) : '',
                            'title' => isset($classes['name']) ? $classes['name'] : '',
                            'href' => "/pages/eventDetails/eventDetails?classes_id=".$classes['id']."&table_type=".$autoplan['table_type']."&t_id=".$autoplan['id'],
                            ];
                    }
                }
            }


            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $data
            ]);
        } catch (Exception $e) {
            return json([
                'code' => 500,
                'msg' => '获取数据失败：' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 获取首页列表数据
     * @return \think\response\Json
     */
    public function getList()
    {
        try {
            $page = input('page', 1);
            $limit = input('limit', 10);
            $latitude = input('latitude', '');
            $longitude = input('longitude', '');

            // 这里可以根据经纬度获取相关数据
            $data = [
                'list' => [],
                'total' => 0,
                'page' => $page,
                'limit' => $limit
            ];

            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $data
            ]);
        } catch (Exception $e) {
            return json([
                'code' => 500,
                'msg' => '获取数据失败：' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 获取城市列表
     * @return \think\response\Json
     */
    public function getCityList()
    {
        try {
            $cities = Db::name('cityarea')
                ->where('level', 2)
                ->where('status', 1)
                ->order('weigh desc, id asc')
                ->select();

            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $cities
            ]);
        } catch (Exception $e) {
            return json([
                'code' => 500,
                'msg' => '获取城市列表失败：' . $e->getMessage(),
                'data' => []
            ]);
        }
    }

    /**
     * 根据经纬度获取城市信息
     * @return \think\response\Json
     */
    public function getCityByLocation()
    {
        try {
            $latitude = input('latitude', '');
            $longitude = input('longitude', '');

            if (empty($latitude) || empty($longitude)) {
                return json([
                    'code' => 400,
                    'msg' => '经纬度参数不能为空',
                    'data' => null
                ]);
            }

            // 这里可以调用第三方API或根据经纬度计算最近的城市
            // 暂时返回默认城市信息
            $cityInfo = [
                'city' => '北京市',
                'cityCode' => '110000',
                'latitude' => $latitude,
                'longitude' => $longitude
            ];

            return json([
                'code' => 200,
                'msg' => 'success',
                'data' => $cityInfo
            ]);
        } catch (Exception $e) {
            return json([
                'code' => 500,
                'msg' => '获取城市信息失败：' . $e->getMessage(),
                'data' => null
            ]);
        }
    }
}